#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>

#define N 128

#define ERR_LOG(errmsg) do{\
                             perror(errmsg);\
                             exit(1);\
                          }while(0)

int main(int argc,char const *argv[]){
    if(argc < 3){
        fprintf(stderr,"Usage: %s [ip] [port]\n",argv[0]);
	    exit(1);
    }

    //第一步：创建套接字
    int sockfd;
    if((sockfd = socket(AF_INET,SOCK_DGRAM,0))==-1){
       ERR_LOG("fail to socket");
    }

    //将套接字设置为允许重复使用本机地址(因为没有多台设备充当客户端)或者设置为端口复用
    int on=1;
    if(setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on))<0){
       ERR_LOG("fail to setsockopt");
    }


    //第二步：将套接字与服务器网络信息结构体绑定
    struct sockaddr_in serveraddr;
    socklen_t addrlen = sizeof(serveraddr);

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    serveraddr.sin_port = htons(atoi(argv[2]));
    
    
    if(bind(sockfd,(struct sockaddr *)&serveraddr,addrlen)==-1){
        ERR_LOG("fail to bind");
    }

    
while(1){
    char buf[N] = "";
    struct sockaddr_in clientaddr;
    if(recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr *)&clientaddr,&addrlen)<0)
    {
        ERR_LOG("fail to recvfrom");
    } 
    printf("[%s - %d]: %s\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port),buf);
    
    strcat(buf,"***");

    if(sendto(sockfd,buf,sizeof(buf),0,(struct sockaddr *)&clientaddr,addrlen)<0)
    {
        ERR_LOG("fail to sendto");
    }
}

    close(sockfd);
    return 0;
}

